package cn.schoolwow.quickdao.module.common.query.kit;

import cn.schoolwow.quickdao.domain.database.dql.condition.Condition;
import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickdao.module.database.dql.condition.kit.ConditionImpl;
import cn.schoolwow.quickdao.module.database.parent.kit.DatabaseDAOImpl;
import cn.schoolwow.quickflow.QuickFlow;

import java.util.ArrayList;

public class QueryOperationImpl extends DatabaseDAOImpl implements QueryOperation{

    public QueryOperationImpl(QuickFlow quickFlow) {
        super(quickFlow);
    }

    @Override
    public <T> Condition<T> query(Class<T> clazz) {
        Entity entity = quickDAOConfig.getEntityByClassName(clazz.getName());
        if (null == entity) {
            throw new IllegalArgumentException("不存在的实体类:" + clazz.getName() + "!");
        }
        return query(entity);
    }

    @Override
    public Condition query(String tableName) {
        Entity entity = quickDAOConfig.getDatabaseEntityByTableName(tableName);
        if (null == entity) {
            for (String virtualTableName : quickDAOConfig.databaseOption.virtualTableNameList) {
                if (virtualTableName.equalsIgnoreCase(tableName)) {
                    entity = new Entity();
                    entity.tableName = virtualTableName;
                    entity.properties = new ArrayList<>();
                    break;
                }
            }
        }
        if (null == entity) {
            throw new IllegalArgumentException("不存在的表名:" + tableName + "!");
        }
        return query(entity);
    }

    @Override
    public Condition query(Condition condition) {
        Condition fromCondition = new ConditionImpl<>(condition, quickFlow, quickDAOConfig);
        return fromCondition;
    }

    private Condition query(Entity entity) {
        Condition condition = new ConditionImpl<>(entity, quickFlow, quickDAOConfig);
        return condition;
    }
}
